import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import router from '@/router'
import store from './store'
import getPageTitle from './utils/get-page-title'
// 定义白名单
const whiteList = ['/login', '404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  console.log(to, '到这里去')
  console.log(from, '从哪里来')
  // 设置页面标题
  document.title = getPageTitle(to.meta.title)
  next()
  // 判断是否有token
  const token = store.state.user.token
  if (token) {
    console.log('已经登录')
    // 判断是否去登录页
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      // 触发action,获取用户信息,存储到vuex当中
      // await添加异步实现页面跳转
      await store.dispatch('user/getUserInfo')
      next()
    }
  } else {
    console.log('没有登录')
    // 判断是否拥有白名单
    if (whiteList.includes(to.path)) {
      // 拥有白名单,放行
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
}
)
router.afterEach(() => {
  NProgress.done()
})
